package wpp.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;

import org.apache.log4j.Logger;

public class IOUtil {
	
	private static final Logger LOGGER = Logger.getLogger(IOUtil.class);
	
	public static File createDirIfNotExists(File file) throws IOException {
		return createIfNotExists(file, true);
	}
	
	public static File createDirIfNotExists(String path) throws IOException {
		return createDirIfNotExists(new File(path));
	}
	
	public static File createFileIfNotExists(File file) throws IOException {
		return createIfNotExists(file, false);
	}
	
	public static File createFileIfNotExists(String path) throws IOException {
		return createFileIfNotExists(new File(path));
	}
	
	public static String readText(InputStream in) throws IOException {		
		StringBuilder sb = new StringBuilder();
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));			
		char[] cs = new char[100];
		int i = 0;
		while((i = reader.read(cs)) != -1 ) {
			sb.append(cs, 0, i);
		}
		return sb.toString();
	}
	
	public static void writeText(OutputStream out, String content) throws IOException {
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
		writer.write(content);	
		writer.flush();
	}
	
	public static void downloadFileFromURL(String path, String urlStr) throws IOException {
		InputStream in = null;
		try {
			URL url = new URL(urlStr);
			in = url.openStream();
			saveFile(path, in);
		} finally {
			if(in != null) {
				in.close();
			}
		}
	}

	public static void saveFile(String path, InputStream in) throws IOException {
		saveFile(path, in, true);
	}
	
	public static void saveFile(String path, InputStream in, boolean override) throws IOException {
		BufferedInputStream bufferedIn = new BufferedInputStream(in);
		BufferedOutputStream bufferedOut = null;
		try {
			createFileIfNotExists(path);
			bufferedOut = new BufferedOutputStream(new FileOutputStream(path));
			int c = 0;
			byte[] bs = new byte[100];
			while(( c = bufferedIn.read(bs)) != -1) {
				bufferedOut.write(bs, 0, c);
			}
			bufferedOut.flush();
		} finally {
			if(bufferedOut != null) {
				try {
					bufferedOut.close();
				} catch (IOException e) {
					LOGGER.error(e.getMessage(), e);
				}
			}
		}
	}
	
	
	//Private
	private static File createIfNotExists(File file, Boolean isDir) throws IOException {
		if(!file.exists()) {
			if(isDir) {
				file.mkdir();
			} else {
				file.createNewFile();
			}
		}
		return file;
	}	
}
